<template>
  <div>
    <Card>
      <tables ref="tables" editable searchable search-place="top" v-model="tableData" :columns="columns" />
      <Button style="margin: 10px 0;" type="primary" @click="exportExcel">导出为excel文件</Button>
      <Button style="position:absolute; top: 27px; right: 17px;" type="primary" @click="addMachineGroup">新增机器</Button>
    </Card>
    <Modal width="900" v-model="visible" :title="title" :mask-closable="false" @on-ok="okModal" @on-cancel="cancelModal">
      <Row>
        <Col span="12">
        <Row class="row" style="margin-top:0;">
          <Col span="6">
          <strong class="title">机器组名：</strong>
          </Col>
          <Col span="18">
          <Select v-model="machineGroupName" placeholder="请选择机器分组" class="form">
            <Option v-for="item in machineGroupNameList" :value="item.value" :key="item.value">{{ item.label }}</Option>
          </Select>
          </Col>
        </Row>
        <Row class="row">
          <Col span="6">
          <strong class="title">机器编号：</strong>
          </Col>
          <Col span="18">
          <Input v-model="machineNumber" placeholder="请输入机器编号，如：ATR00001" class="form" />
          </Col>
        </Row>
        <Row class="row">
          <Col span="6">
          <strong class="title">机器名：</strong>
          </Col>
          <Col span="18">
          <Input v-model="machineName" placeholder="请输入机器名" class="form" />
          </Col>
        </Row>
        <Row class="row">
          <Col span="6">
          <strong class="title">厢体ID：</strong>
          </Col>
          <Col span="18">
          <Input v-model="carbodyID" placeholder="请输入厢体ID" class="form" />
          </Col>
        </Row>
        <Row class="row">
          <Col span="6">
          <strong class="title">账号锁定：</strong>
          </Col>
          <Col span="18">
          <Select v-model="accountLockout" placeholder="请选择账号锁定" class="form">
            <Option v-for="item in machineLockList" :value="item.value" :key="item.value">{{ item.label }}</Option>
          </Select>
          </Col>
        </Row>
        <Row class="row">
          <Col span="6">
          <strong class="title">部署地址：</strong>
          </Col>
          <Col span="18">
          <Input v-model="deployAddress" placeholder="请输入部署地址" class="form" />
          </Col>
        </Row>
        </Col>
        <Col span="12">
        <Row class="row" style="margin-top:0;">
          <Col span="6">
          <strong class="title">经度：</strong>
          </Col>
          <Col span="18">
          <Input v-model="longitude" placeholder="请输入经度" class="form" />
          </Col>
        </Row>
        <Row class="row">
          <Col span="6">
          <strong class="title">纬度：</strong>
          </Col>
          <Col span="18">
          <Input v-model="latitude" placeholder="请输入纬度" class="form" />
          </Col>
        </Row>
        <Row class="row">
          <Col span="6">
          <strong class="title">自动退款次数：</strong>
          </Col>
          <Col span="18">
          <InputNumber v-model="refund" placeholder="请输入机器出货网络异常自动退款次数" class="form" />
          </Col>
        </Row>
        <Row class="row">
          <Col span="6">
          <strong class="title">收款方式：</strong>
          </Col>
          <Col span="18">
          <Select v-model="collectionType" placeholder="请选择收款方式" class="form" @on-change="handleTypeChange">
            <Option v-for="item in collectionTypeList" :value="item.value" :key="item.value">{{ item.label }}</Option>
          </Select>
          </Col>
        </Row>
        <Row class="row">
          <Col span="6">
          <strong class="title">收款账户：</strong>
          </Col>
          <Col span="18">
          <Input disabled v-model="collectionAccount" placeholder="请输入收款账户" class="form" />
          </Col>
        </Row>
        <Row class="row">
          <Col span="6">
          <strong class="title">便利店购物车：</strong>
          </Col>
          <Col span="18">
          <Select v-model="shoppingCar" placeholder="请选择便利店购物车状态" class="form">
            <Option v-for="item in doorStateList" :value="item.value" :key="item.value">{{ item.label }}</Option>
          </Select>
          </Col>
        </Row>
        <Row class="row">
          <Col span="6">
          <strong class="title">是否支持预定：</strong>
          </Col>
          <Col span="18">
          <Select v-model="preorder" placeholder="请选择是否支持预定" class="form">
            <Option v-for="item in doorStateList" :value="item.value" :key="item.value">{{ item.label }}</Option>
          </Select>
          </Col>
        </Row>
        </Col>
      </Row>
    </Modal>
    <Modal v-model="deleteVisible" @on-ok="handleDelete">
      <p>是否确定删除该条记录？</p>
    </Modal>
  </div>
</template>

<script>
import Mock from 'mockjs'
import Tables from '_c/tables'
import {
  machineGroupNameValues,
  machineNumberList,
  machineNumberValues,
  switchList,
  switchValues,
  whetherList,
  whetherValues,
  lockList,
  lockValues,
  machineLockList,
  machineLockValues,
  doorStates,
  doorStateList,
} from '@/mock/data/option-data.js';
import rcRequest from 'rc-request'
import jsCookie from 'js-cookie'

// TODO: 设置收款方式

export default {
  name: 'commodity_type_page',
  components: {
    Tables
  },
  data() {
    return {
      columns: [
        { title: '机器组名', key: 'machineGroupName' },
        { title: '机器编号', key: 'machineNumber' },
        { title: '机器名', key: 'machineName' },
        { title: '厢体ID', key: 'carbodyID' },
        { title: '机器锁定', key: 'accountLockout' },
        { title: '部署地址', key: 'deployAddress' },
        { title: '经度', key: 'longitude' },
        { title: '纬度', key: 'latitude' },
        { title: '机器出货网络异常自动退款次数', key: 'refund' },
        { title: '收款方式', key: 'collectionType' },
        { title: '收款账户', key: 'collectionAccount' },
        { title: '便利店购物车', key: 'shoppingCar' },
        { title: '是否支持预定', key: 'preorder' },
        {
          title: '操作',
          key: 'action',
          width: 140,
          render: (h, params) => {
            return h('div', [
              h('Button', {
                props: {
                  type: 'info',
                  size: 'small',
                  ghost: true,
                },
                on: {
                  click: () => {
                    this.title = '修改机器';
                    this.visible = true;
                    this.machineGroupName = params.row.machine_group_id;
                    this.machineNumber = params.row.machineNumber;
                    this.machineName = params.row.machineName;
                    this.carbodyID = params.row.carbodyID;
                    this.accountLockout = params.row.lock_status;
                    this.deployAddress = params.row.deployAddress;
                    this.longitude = params.row.longitude;
                    this.latitude = params.row.latitude;
                    this.refund = params.row.refund;
                    this.collectionType = params.row.collectionTypeId,
                      this.collectionAccount = params.row.collectionAccount;
                    this.shoppingCar = params.row.is_shopping_cart;
                    this.preorder = params.row.is_reserve;
                    this.machineGroupIndex = params.row.initRowIndex;
                  }
                }
              }, '修改'),
              h('span', {}, ' '),
              h('Button', {
                props: {
                  type: 'warning',
                  size: 'small',
                  ghost: true,
                },
                on: {
                  click: () => {
                    this.deleteIndex = params.row.initRowIndex;
                    this.deleteVisible = true;
                  }
                },
              }, '删除')
            ]);
          }
        }
      ],
      tableData: [],
      machineGroupNameList: [],
      collectionTypeList: [],
      machineNumberList,
      switchList,
      whetherList,
      lockList,
      machineLockList,
      doorStateList,
      // 新增/修改机器
      title: '新增机器',
      visible: false,
      machineGroupName: '', // 机器组名
      machineNumber: '',  // 机器编号
      machineName: '', // 机器名
      carbodyID: '', // 厢体ID
      accountLockout: '', // 账号是否锁定
      deployAddress: '', // 部署地址
      longitude: '', // 经度
      latitude: '', // 纬度
      refund: 0, // 机器出货网络异常自动退款次数
      collectionType: '', // 收款方式
      collectionAccount: '', // 收款账户
      shoppingCar: '', // 便利店购物车
      preorder: '', // 是否支持预定
      machineGroupIndex: -1,
      // 删除
      deleteVisible: false,
      deleteIndex: 0,
    }
  },
  methods: {
    exportExcel() {
      this.$refs.tables.exportCsv({
        filename: `机器-${(new Date()).valueOf()}.csv`
      })
    },

    addMachineGroup() {
      this.title = '新增机器';
      this.visible = true;
      this.machineGroupName = '';
      this.machineNumber = '';
      this.machineName = '';
      this.carbodyID = '';
      this.accountLockout = '';
      this.deployAddress = '';
      this.longitude = '';
      this.latitude = '';
      this.refund = 0;
      this.collectionType = '';
      this.collectionAccount = '';
      this.shoppingCar = '';
      this.preorder = '';
      this.machineGroupIndex = -1;
    },

    async okModal() {
      // 新增
      if (this.machineGroupIndex < 0) {
        const { data: { code, msg } } = await rcRequest({
          method: 'post',
          url: '/machine/insert_machine_info',
          data: {
            machine_group_id: this.machineGroupName,
            name: this.machineName,
            number: this.machineNumber,
            bodyID: this.carbodyID,
            lock_status: this.accountLockout,
            addr: this.deployAddress,
            longitude: this.longitude,
            latitude: this.latitude,
            automatic_refunds: this.refund,
            collection_type_id: this.collectionType,
            is_shopping_cart: this.shoppingCar,
            is_reserve: this.preorder,
            paper_money_machine: '0',
            coin_machine: '0',
            card_reader: '0',
          },
        })

        if (code != 200) {
          this.$Message.error(msg)
          return
        }

        this.getListData()
        this.$Message.success('新增成功')
        return;
      }

      // 修改
      const { data: { code, msg } } = await rcRequest({
        method: 'post',
        url: '/machine/update_machine_info2',
        data: {
          machine_id: this.tableData[this.machineGroupIndex].id,
          old_machine_group_id: this.tableData[this.machineGroupIndex].machine_group_id,
          new_machine_group_id: this.machineGroupName,
          machine_or_machine_group_id: this.tableData[this.machineGroupIndex].machine_or_machine_group_id,
          name: this.machineName,
          number: this.machineNumber,
          bodyID: this.carbodyID,
          lock_status: this.accountLockout,
          addr: this.deployAddress,
          longitude: this.longitude,
          latitude: this.latitude,
          automatic_refunds: this.refund,
          collection_type_id: this.collectionType,
          old_collection_type_id: this.tableData[this.machineGroupIndex].collection_type_id,
          machine_or_collection_type_id: this.tableData[this.machineGroupIndex].machine_or_collection_type_id,
          is_shopping_cart: this.shoppingCar,
          is_reserve: this.preorder,
        },
      })

      if (code != 200) {
        this.$Message.error(msg)
        return
      }

      this.getListData()
      this.$Message.success('修改成功')
    },

    cancelModal() { },

    // 修改收款方式
    handleTypeChange(value) {
      this.collectionTypeList.map(item => {
        if (item.value == value) {
          this.collectionAccount = item.number;
          return;
        }
      })
    },
    
    // 获取机器组列表数据
    async getGroupListData() {
      const { data: { data: groupResult } } = await rcRequest({
        method: 'post',
        data: {},
        url: '/machine_group/select_machinegroup_name',
      });
      this.machineGroupNameList = groupResult.map(item => ({ value: item.id, label: item.name }));
    },

    // 获取收款方式列表数据
    async getCollectionTypeListData() {
      const { data: { data: typesResult } } = await rcRequest({
        method: 'post',
        data: {},
        url: '/payargument/select_collection_type_list',
      });
      this.collectionTypeList = typesResult.map(item => ({
        value: item.id,
        label: item.name,
        number: item.bank_number,
      }));
    },

    // 获取列表数据
    async getListData() {
      const { data: { data } } = await rcRequest({
        method: 'post',
        url: '/machine/select_machine_list',
        data: {}
      })
      this.tableData = data.map(item => ({
        id: item.id,
        machineGroupName: item.machine_group_name,
        machine_group_id: item.machine_group_id,
        machineNumber: item.number,
        machineName: item.name,
        carbodyID: item.bodyID,
        accountLockout: machineLockValues[item.lock_status],
        lock_status: item.lock_status,
        deployAddress: item.addr,
        longitude: item.longitude,
        latitude: item.latitude,
        refund: item.automatic_refunds,
        collectionType: item.collection_type_name,
        collectionTypeId: item.collection_type_id,
        collectionAccount: item.bank_number,
        shoppingCar: doorStates[item.is_shopping_cart],
        is_shopping_cart: item.is_shopping_cart,
        preorder: doorStates[item.is_reserve],
        is_reserve: item.is_reserve,
        machine_or_machine_group_id: item.machine_or_machine_group_id,
        machine_or_collection_type_id: item.machine_or_collection_type_id,
      }))
    },

    // 删除数据
    async handleDelete() {
      const { data: { code, msg } } = await rcRequest({
        method: 'post',
        url: '/machine/delete_machine_info',
        data: { 
          machine_id: this.tableData[this.deleteIndex].id,
          machine_group_id: this.tableData[this.deleteIndex].machine_group_id,
        },
      })

      if (code != 200) {
        this.$Message.error(msg)
        return
      }

      this.tableData.splice(this.deleteIndex, 1)
      this.$Message.success(msg)
    },
  },
  mounted() {
    this.getListData()
    this.getGroupListData()
    this.getCollectionTypeListData()
  }
}
</script>

<style scoped>
.row {
  margin-top: 20px;
  display: flex;
  align-items: center;
}

.title {
  display: flex;
  justify-content: flex-end;
  padding-right: 20px;
}

.form {
  width: 85%;
}
</style>
